# vim:set ft=dockerfile:
FROM walg-func-test-base as build

ARG WALG_REPO=${GOPATH}/src/github.com/wal-g/wal-g
ENV USE_BROTLI 1

RUN mkdir -p ${WALG_REPO}
COPY staging/wal-g ${WALG_REPO}/

WORKDIR ${WALG_REPO}

RUN make link_external_deps && \
    make BUILD_ARGS=-race mongo_build && \
    cp main/mongo/wal-g /usr/bin/wal-g

###

FROM ubuntu:focal

COPY --from=build /usr/bin/wal-g /usr/bin/wal-g

ENV DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC

ARG MONGO_PACKAGE=mongodb-org
ARG MONGO_REPO=repo.mongodb.org
ENV MONGO_PACKAGE=${MONGO_PACKAGE} MONGO_REPO=${MONGO_REPO}
ARG MONGO_MAJOR=
ARG MONGO_VERSION=

ENV TMP_DIR /var/tmp/wal-g
ENV WALG_CONF_DIR /etc/wal-g/

RUN apt-get update -q && \
    apt-get install --yes --no-install-recommends --no-install-suggests \
    supervisor ca-certificates libsasl2-modules-gssapi-mit snmp wget gnupg curl tzdata && \
    echo "deb http://$MONGO_REPO/apt/ubuntu focal/${MONGO_PACKAGE}/${MONGO_MAJOR} multiverse" | tee "/etc/apt/sources.list.d/mongodb_${MONGO_MAJOR}.list" && \
    wget -qO - https://www.mongodb.org/static/pgp/server-${MONGO_MAJOR}.asc | apt-key add - && \
    apt-get update -q && \
    apt-get download --allow-unauthenticated ${MONGO_PACKAGE}-server=$MONGO_VERSION && \
    dpkg --unpack ${MONGO_PACKAGE}-server*.deb && \
    sed -i 's/systemctl daemon-reload/echo "SKIPPED: systemctl daemon-reload"/' /var/lib/dpkg/info/${MONGO_PACKAGE}-server.postinst && \
    dpkg --configure ${MONGO_PACKAGE}-server && \
    apt-get install -yf && \
    apt-get install --allow-unauthenticated -y mongodb-database-tools && \
    apt-get install -y mongodb-mongosh && \
    rm -rf /var/lib/apt/lists/* /var/cache/debconf /var/lib/mongodb/* && \
    apt-get clean

COPY images/base/config/supervisor /etc/supervisor
COPY images/mongodb/config /config
COPY images/mongodb/config/mongodb.keyfile /etc/mongodb/

RUN chmod 700 /etc/mongodb/mongodb.keyfile && chown mongodb -R /etc/mongodb && \
    mkdir -p /home/mongodb /var/log/wal-g/ ${TMP_DIR} && \
    chown mongodb:mongodb /home/mongodb /var/log/wal-g/ && \
    ln --force -s /config/supervisor/conf.d/mongodb.conf /etc/supervisor/conf.d/mongodb.conf && \
    mkdir -p ${WALG_REPO} ${WALG_CONF_DIR} && \
    mkdir -p /home/mongodb/.gnupg && touch /home/mongodb/.gnupg/gpg.conf && \
    chmod -R 700 /home/mongodb/.gnupg && chown mongodb:mongodb -R /home/mongodb/.gnupg && \
    ln --force -s /config/wal-g-${MONGO_MAJOR}.json ${WALG_CONF_DIR}/wal-g.json && \
    ln --force -s /config/gpg-key.armor ${WALG_CONF_DIR}/gpg-key.armor

CMD ["supervisord", "-c", "/etc/supervisor/supervisord.conf"]
